import sys
import os

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database

class StudentDeleter:
    def __init__(self):
        self.db = Database()
    
    def delete_student(self, student_id):
        """
        删除学生信息
        
        参数:
            student_id (str): 学号
        
        返回:
            bool: 删除成功返回True，否则返回False
        """
        try:
            # 验证输入
            if not student_id:
                print("错误：学号必须填写")
                return False
            
            # 连接数据库
            self.db.connect()
            
            # 检查学生是否存在
            self.db.cursor.execute(
                "SELECT id, name, dormitory_id FROM student WHERE student_id = ?",
                (student_id,)
            )
            student = self.db.cursor.fetchone()
            
            if not student:
                print(f"错误：学号为 {student_id} 的学生不存在")
                return False
            
            student_db_id, name, dormitory_id = student
            
            # 检查学生是否已分配宿舍
            if dormitory_id:
                print(f"错误：学生 {name}（学号：{student_id}）已分配宿舍，请先处理退宿")
                return False
            
            # 删除学生
            self.db.cursor.execute(
                "DELETE FROM student WHERE id = ?",
                (student_db_id,)
            )
            self.db.conn.commit()
            
            print(f"成功：学生 {name}（学号：{student_id}）已删除")
            return True
        except Exception as e:
            print(f"错误：删除学生时发生错误 - {str(e)}")
            return False
        finally:
            self.db.close()
    
    def delete_students(self, student_ids):
        """
        批量删除学生信息
        
        参数:
            student_ids (list): 学号列表
        
        返回:
            tuple: (成功删除数量, 总数量)
        """
        success_count = 0
        total_count = len(student_ids)
        
        try:
            self.db.connect()
            
            for student_id in student_ids:
                # 检查学生是否存在
                self.db.cursor.execute(
                    "SELECT id, name, dormitory_id FROM student WHERE student_id = ?",
                    (student_id,)
                )
                student = self.db.cursor.fetchone()
                
                if not student:
                    print(f"错误：学号为 {student_id} 的学生不存在")
                    continue
                
                student_db_id, name, dormitory_id = student
                
                # 检查学生是否已分配宿舍
                if dormitory_id:
                    print(f"错误：学生 {name}（学号：{student_id}）已分配宿舍，请先处理退宿")
                    continue
                
                # 删除学生
                self.db.cursor.execute(
                    "DELETE FROM student WHERE id = ?",
                    (student_db_id,)
                )
                self.db.conn.commit()
                
                print(f"成功：学生 {name}（学号：{student_id}）已删除")
                success_count += 1
            
            return success_count, total_count
        except Exception as e:
            print(f"错误：批量删除学生时发生错误 - {str(e)}")
            return success_count, total_count
        finally:
            self.db.close()

# 如果直接运行此文件，提供命令行界面
if __name__ == "__main__":
    deleter = StudentDeleter()
    
    print("===== 学生信息删除 =====")
    print("1. 删除单个学生")
    print("2. 批量删除学生")
    
    choice = input("请选择操作 (1-2): ")
    
    if choice == '1':
        student_id = input("请输入学号: ")
        deleter.delete_student(student_id)
    
    elif choice == '2':
        # 先查询所有学生
        from query_student import StudentQuery
        query = StudentQuery()
        students = query.query_all_students()
        
        if not students:
            print("没有找到任何学生信息")
        else:
            print("\n学生ID\t学号\t姓名\t性别\t班级\t联系方式\t宿舍ID")
            for student in students:
                dormitory_id = student[6] if student[6] else "未分配"
                print(f"{student[0]}\t{student[1]}\t{student[2]}\t{student[3]}\t{student[4]}\t{student[5] or '无'}\t{dormitory_id}")
            
            ids_input = input("\n请输入要删除的学生学号，多个学号用逗号分隔: ")
            student_ids = [id.strip() for id in ids_input.split(',')]
            success_count, total_count = deleter.delete_students(student_ids)
            print(f"\n批量删除完成：成功 {success_count}/{total_count}")
    
    else:
        print("无效的选择")